package file

import (
	"fmt"
	"log"
	"regexp"
	"strconv"
	"time"
	"tyy_linux_system/models"
)

func isMatchRefuseConnect(strRet []string) (bool, []string) {
	matchStrRet := make([]string, 0)
	refuseConnectRe := regexp.MustCompile(`refused connect from`)
	for _, str := range strRet {
		if len(refuseConnectRe.FindStringSubmatch(str)) > 0 {
			matchStrRet = append(matchStrRet, str)
		}
	}
	if len(matchStrRet) > 0 {
		return true, matchStrRet
	} else {
		return false, nil
	}
}

// YYYY-MM-DD HH:MM:SS
func matchRefuseConnect(strRet []string) []*models.RefuseConnectFrom {
	RefuseConnectFromModelRet := make([]*models.RefuseConnectFrom, 0)
	monthRe := regexp.MustCompile(`^\w+\s+\d+`)
	spaceRe := regexp.MustCompile(`\s+`)
	timeRe := regexp.MustCompile(`\d+\:\d+\:\d+`)
	ipRe := regexp.MustCompile(`\d+\.\d+\.\d+\.\d+`)
	for _, str := range strRet {
		refuseConnectFromModel := &models.RefuseConnectFrom{}
		monthDate := monthRe.FindStringSubmatch(str)
		timeList := timeRe.FindStringSubmatch(str)
		if len(monthDate) > 0 && len(timeList) > 0 {
			year := time.Now().Format("2006")
			month := time.Now().Format("01")
			_, date := spaceRe.Split(monthDate[0], -1)[0], spaceRe.Split(monthDate[0], -1)[1]
			date_02, _ := strconv.Atoi(date)
			time := timeList[0]
			refuseTime := fmt.Sprintf("%s-%s-%02d %s", year, month, date_02, time)
			log.Println(refuseTime)
			refuseConnectFromModel.RefuseTime = refuseTime
		}
		ip := ipRe.FindStringSubmatch(str)
		if len(ip) > 0 {
			refuseConnectFromModel.IP = ip[0]
		}
		RefuseConnectFromModelRet = append(RefuseConnectFromModelRet, refuseConnectFromModel)
	}
	return RefuseConnectFromModelRet
}
